package com.seal.tsms.school.controller;

import com.seal.tsms.base.controller.BaseController;
import com.seal.tsms.base.service.BaseService;
import com.seal.tsms.school.entity.RelationInfo;
import com.seal.tsms.school.service.RelationInfoService;
import org.hibernate.criterion.DetachedCriteria;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.xml.sax.SAXException;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hhw on 2016/1/22.
 * 联系信息Controller
 */
@Controller
@RequestMapping("/school/relationInfo")//等同于namespace
public class RelationInfoController extends BaseController<RelationInfo,String> {

    @Override
    @Autowired
    @Qualifier("relationInfoServiceImpl")
    public void setSelfService(BaseService<RelationInfo, String> selfService) {
        super.setSelfService(selfService);
    }

    @RequestMapping(value = "/addUI", method = RequestMethod.GET)//等同与action的name属性
    public String create() {
        return "school/relationInfo/add";//视图路径
    }

    @RequestMapping(value = "/addUI", method = RequestMethod.POST)
    public String save(@ModelAttribute("relationInfo") RelationInfo relationInfo, RedirectAttributes attr) {

        getSelfService().save(relationInfo);
        attr.addAttribute("id", relationInfo.getId());
        attr.addFlashAttribute("msg", "联系信息添加成功");

        return "redirect:/school/relationInfo/show.do";
    }

    @RequestMapping(value = "/show")
    public String show(@RequestParam String id, ModelMap model) {
        model.addAttribute("relationInfo", getSelfService().get(id));
        return "/school/relationInfo/show";
    }

    @RequestMapping(value="/importExcel",method = RequestMethod.GET)
    public String toImportExcel(){
        return "school/relationInfo/import";
    }

    //导入excel
    @RequestMapping(value = "/importExcel",method = RequestMethod.POST)
    public String importExcel(@RequestParam(value = "file")MultipartFile file, HttpServletRequest request,RedirectAttributes attr){
        //获取excel文件的路径
        String path = request.getServletContext().getRealPath("/static/xls");

        String fileName = file.getOriginalFilename();//获得文件名称

        File targetFile = new File(path,fileName);//创建一个文件对象

        if(!targetFile.exists()){
            targetFile.mkdirs();
        }

        try {
            file.transferTo(targetFile);//将文件内容拷贝到新创建的文件中

            InputStream inputXml = new BufferedInputStream(getClass().getResourceAsStream("/xml/xls-template/relationInfo.xml"));
            XLSReader mainReader = ReaderBuilder.buildFromXML(inputXml);
            InputStream inputXls = new BufferedInputStream(new FileInputStream(targetFile));

            List<RelationInfo> relationInfos = new ArrayList<RelationInfo>();
            Map beans = new HashMap();

            beans.put("relationInfos",relationInfos);
            ReaderConfig.getInstance().setSkipErrors(true);
            ReaderConfig.getInstance().setUseDefaultValuesForPrimitiveTypes(true);
            XLSReadStatus readStatus = mainReader.read(inputXls,beans);

            ((RelationInfoService)getSelfService()).saveList(relationInfos);

            attr.addFlashAttribute("msg","导入成功!");

        } catch (Exception e) {
            attr.addFlashAttribute("msg","导入失败!");
            log.error("导入失败",e);
        }

        return "redirect:/school/relationInfo/success.do";
    }

    //导出excel
    @RequestMapping(value = "/exportExcel")
    public String exportExcel(HttpServletRequest request,RedirectAttributes attr){
        InputStream is=null;
        OutputStream os=null;

        List<RelationInfo> relationInfos = (List<RelationInfo>) getSelfService().list(DetachedCriteria.forClass(RelationInfo.class),null);

        try {
            is=getClass().getResourceAsStream("/xml/xls-template/relationInfo-export.xls");

            os=new FileOutputStream("d:/git/export.xls");

            Context context = new Context();
            context.putVar("relationInfos",relationInfos);
            JxlsHelper.getInstance().processTemplateAtCell(is,os,context,"学院档案!A1");

            attr.addFlashAttribute("msg","导出成功");
        } catch (Exception e) {
            log.error("导出失败",e);
            attr.addFlashAttribute("msg","导出失败!");
        } finally{
            try {
                os.close();

                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

        return "redirect:/school/relationInfo/success.do";
    }

    @RequestMapping(value = "/success")
    public String success(){
        return "/school/relationInfo/success";
    }
}